const { WebSocketServer } = require("ws");
const WebSocket = require("ws");
const wss = new WebSocketServer({
  port: 8080,
});
let users = [];

wss.on("connection", (ws, req) => {
  console.log("客户端已连接：", req.socket.remoteAddress); // 获取客户端 ip

  ws.on("message", (res) => {
    const data = JSON.parse(res.toString());
    console.log("收到客户端发送的消息：", data);

    if (data.type == "online") { 
      users.push(data);
    } else if (data.type == "offline") {
      users = users.filter((item) => item.username != data.username);
    } else if (data.type == "msg") {
      // console.log("已连接客户端", wss.clients);
      wss.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN) {
          client.send(JSON.stringify(data));
        }
      });
      // ws.send(data);
    }

    // ws.send("我是服务端"); // 向当前客户端发送消息
  });

  ws.on("error", (err) => {
    console.log("连接出错：", err);
  });
  ws.on("close", (e) => {
    console.log("客户端断开：", e);
  });
});
